<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用then的链式调用解决回调地狱</title>
</head>
<body>
<script type="text/javascript">
    // Promise 如何串连多个异步任务？------通过 then 的链式调用
    function sendAjax(url, data) {
        return new Promise((resolve, reject) => {
            // 实例 xhr
            const xhr = new XMLHttpRequest()
            // 绑定监听
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) resolve(xhr.response)
                    else reject('请求出了点问题')
                }
            }
            // 整理参数
            let str = ''
            for (let key in data) {
                str += `${key}=${data[key]}`
            }
            str = str.slice(0, -1)
            xhr.open('GET', url + '?' + str)
            xhr.responseType = 'json'
            xhr.send()
        })
    }

    // 发送第 1 次请求
    sendAjax('https://api.apiopen.top/api/getHaoKanVideo', {page: 2, size: 5})
        .then(
            value => {
                console.log('第1次请求成功了', value)
                return sendAjax('https://api.apiopen.top/api/getHaoKanVideo', {page: 2, size: 5})
            },
            reason => {
                console.log('第1次请求失败了', reason)
            }
        )
        .then(
            value => {
                console.log('第二次请求成功了', value)
                return sendAjax('https://api.apiopen.top/api/getHaoKanVideo', {page: 2, size: 5})
            },
            reason => {
                console.log('第二次请求失败了', reason)
            }
        )
        .then(
            value => {
                console.log('第三次请求成功了', value)
            },
            reason => {
                console.log('第三次请求失败了', reason)
            }
        )
</script>
</body>
</html>
